#!/usr/bin/env bash
set +o posix # rpm uses /bin/sh that forces bash in posix mode
set -eo pipefail; [[ $TRACE ]] && set -x

setup-user() {
  echo "Setting up dokku user"
  getent passwd dokku >/dev/null || useradd -m -s /bin/bash dokku
  usermod -aG docker dokku
  mkdir -p "$DOKKU_ROOT/.ssh" "$DOKKU_ROOT/.dokkurc"
  touch "$DOKKU_ROOT/.ssh/authorized_keys"
  chown -R dokku:dokku "$DOKKU_ROOT/.ssh" "${DOKKU_ROOT}/.dokkurc"
}

setup-storage() {
  echo "Setting up storage directories"
  mkdir -p "${DOKKU_LIB_ROOT}/data" "${DOKKU_LIB_ROOT}/data/storage"
  chown dokku:dokku -R "${DOKKU_LIB_ROOT}/data"
}

setup-plugins() {
  echo "Setting up plugin directories"
  # should be replaced by `plugn init`
  mkdir -p "${DOKKU_LIB_ROOT}/core-plugins/available" "${DOKKU_LIB_ROOT}/plugins/available"
  mkdir -p "${DOKKU_LIB_ROOT}/core-plugins/enabled" "${DOKKU_LIB_ROOT}/plugins/enabled"
  touch "${DOKKU_LIB_ROOT}/core-plugins/config.toml" "${DOKKU_LIB_ROOT}/plugins/config.toml"

  echo "Migrating old plugins"
  find ${DOKKU_LIB_ROOT}/plugins/ -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | while read -r plugin; do
    if [ "$plugin" = "available" ] || [ "$plugin" = "enabled" ]; then
      continue
    elif [ -f ${DOKKU_LIB_ROOT}/plugins/$plugin/.core ]; then
      rm -rf ${DOKKU_LIB_ROOT}/plugins/$plugin
    elif [ ! -d ${DOKKU_LIB_ROOT}/plugins/available/$plugin ]; then
      mv ${DOKKU_LIB_ROOT}/plugins/$plugin ${DOKKU_LIB_ROOT}/plugins/available
    fi
  done

  echo "Enabling all core plugins"
  find "${DOKKU_LIB_ROOT}/core-plugins/available" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | while read -r plugin; do
    if [ ! -d "${DOKKU_LIB_ROOT}/plugins/available/$plugin" ]; then
      ln -s "${DOKKU_LIB_ROOT}/core-plugins/available/$plugin" "${DOKKU_LIB_ROOT}/plugins/available/$plugin"
      PLUGIN_PATH="${DOKKU_LIB_ROOT}/core-plugins" plugn enable "$plugin"
      PLUGIN_PATH="${DOKKU_LIB_ROOT}/plugins" plugn enable "$plugin"
    fi
  done
  find -L "${DOKKU_LIB_ROOT}" -type l -delete
  chown dokku:dokku -R "${DOKKU_LIB_ROOT}/plugins" "${DOKKU_LIB_ROOT}/core-plugins"

  echo "Install all core plugins"
  dokku plugin:install --core
}

setup-sshcommand() {
  echo "Ensure proper sshcommand path"
  echo '/usr/bin/dokku' >"${DOKKU_ROOT}/.sshcommand"
  if [[ -f .ssh/authorized_keys ]]; then
    sed -i.bak 's#/usr/local/bin/dokku#/usr/bin/dokku#' "${DOKKU_ROOT}/.ssh/authorized_keys"
    rm "${DOKKU_ROOT}/.ssh/authorized_keys"
  fi
}

main() {
  if [[ -r /etc/default/dokku ]]; then
    # shellcheck disable=SC1091
    source /etc/default/dokku
  fi

  readonly DOKKU_ROOT="${DOKKU_ROOT:-/home/dokku}"
  readonly DOKKU_LIB_ROOT="${DOKKU_LIB_PATH:-/var/lib/dokku}"

  setup-user
  setup-storage
  setup-plugins
  setup-sshcommand
}

main
